package controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.BreakIterator;
import java.util.StringTokenizer;

import org.eclipse.swt.SWT;

import artificialIntelligence.AutoSolver;
import model.State;
import server.ClientHandler;
import server.MyServer;
import view.Board;

/**
 * This class responsible for the Solving Server execution.<br>
 * On execution the server handle each client separately, calculating the next highest valued state according to the AI algorithm.<br>
 * Working on Localhost with port 5000 on one client simultaneously. Server waiting for Clients for three minutes.<br>
 * @see ClientHandler
 * @author Barak & Tom
 */
public class ServerExecutor {

	public static void main(String[] args) throws Exception {
		MyServer myServer = new MyServer(5000, new ClientHandler() {
			
			@Override
			public void handleClient(BufferedReader dataFromClient, PrintWriter dataToClient) {
				String clientState;
				try {
						while ((clientState = dataFromClient.readLine()) == null) {
							//Busy Wait
						}
						if (clientState == "done") {
							return;
						}
						//System.out.println("Current client state: " + clientState);
						System.out.println("Current client state received");
						
						//TODO: clientState calculation with AI algorithm
						AutoSolver minimax = new AutoSolver();
						minimax.setDept(Integer.parseInt(clientState.split("\\|")[2]));
						minimax.minimax(new State(0, Integer.parseInt(clientState.split("\\|")[0]),XMLHandler.StringTo2DArray(clientState.split("\\|")[1]), null), Integer.parseInt(clientState.split("\\|")[2]),
								Integer.MIN_VALUE, Integer.MAX_VALUE, true);
						switch (minimax.move) {
						case 0:
							clientState= Integer.toString(SWT.ARROW_DOWN);
							System.out.println("Calculated client next move is Down");
							break;
						case 1:
							clientState= Integer.toString(SWT.ARROW_LEFT);
							System.out.println("Calculated client next move is left");
							break;
						case 2:
							clientState= Integer.toString(SWT.ARROW_RIGHT);
							System.out.println("Calculated client next move is right");
							break;
						case 3:
							clientState= Integer.toString(SWT.ARROW_UP);
							System.out.println("Calculated client next move is up" );
							break;
						default:
							break;
						}
						
						dataToClient.println(clientState);
						dataToClient.flush();

				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		
		}, 3);
			
		myServer.start();
		Thread.sleep((long) (1 * 60 * 1000));

		myServer.close();
	}

}
